﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;

public partial class custom_pages_statdata : System.Web.UI.Page
{
    protected List<string[]> cols = new List<string[]>();
    protected List<object[]> rows = new List<object[]>();

    protected void Page_Load(object sender, EventArgs e)
    {
        DataTable data = LoadData();
        cols.Add(new string[] { data.Columns[0].Caption, "string" });
        for (int i = 1; i < data.Columns.Count; i++)
            cols.Add(new string[] { data.Columns[i].Caption, "number" });
        DataRow[] selection = data.Select(
            "År<>" + DateTime.Now.Year + " OR Måned<>" + DateTime.Now.Month);
        for (int i = 0; i < selection.Length; i++)
            rows.Add(selection[i].ItemArray);
    }

    private TextReader OpenLatestStatistics()
    {
        string filepath = Server.MapPath(ConfigurationManager.AppSettings["datapath"]
            + DateTime.Now.Month + "-" + DateTime.Now.Year + ".csv");
        // Create a local file with the latest statistics if one does not already exist.
        if (!File.Exists(filepath)) {
            TextWriter file = new StreamWriter(filepath);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(
                ConfigurationManager.AppSettings["staturl"]);
            TextReader tr = new StreamReader(request.GetResponse().GetResponseStream());
            file.Write(tr.ReadToEnd());
            file.Close();
            tr.Close();
        }
        return new StreamReader(filepath);
    }

    private DataTable LoadData()
    {
        DataTable dt = new DataTable();
        TextReader tr = OpenLatestStatistics();
        
        string line = tr.ReadLine(); // Header line of the CSV file.
        string[] values = ExtractValuesFromCSV(line, ';');
        dt.Columns.Add(values[0], typeof(string)); // Only the first line is a string.
        for (int i = 1; i < values.Length; i++) dt.Columns.Add(values[i], typeof(double));

        while ((line = tr.ReadLine()) != null) {
            values = ExtractValuesFromCSV(line, ';');
            object[] cells = new object[values.Length];
            cells[0] = values[0]; // First value, parse as string.
            for (int i = 1; i < cells.Length; i++)
                cells[i] = double.Parse(values[i]); // Parse all other values as doubles.
            dt.Rows.Add(cells);
        }
        tr.Close();

        // DEPRECATED 30-05-2012 by JFI.
        // Remove all municipalities not in the XML list from the data set.
        /*XmlDocument xml;
        try {
            xml = new XmlDocument();
            xml.Load(Server.MapPath("~/xml/MunicipalityList.xml"));
        } catch (FileNotFoundException ex) { xml = null; }
        if (xml != null) {
            List<DataRow> removal = new List<DataRow>();
            foreach (DataRow row in dt.Rows) {
                if (xml.SelectSingleNode("//municipality[@name='" + row[0] + "']") == null)
                    removal.Add(row);
            }
            foreach (DataRow row in removal) dt.Rows.Remove(row);
        }*/
        
        return dt;
    }

    private string[] ExtractValuesFromCSV(string line, char delimiter)
    {
        string[] values = line.Split(delimiter);
        for (int i = 0; i < values.Length; i++) {
            values[i] = values[i].Trim(new char[] { '"' });
            values[i] = values[i].TrimEnd(new char[] { '%' });
            if (values[i].Length == 0) values[i] = "0";
        }
        return values;
    }
}